<template>
  <a-form
    :model="WBTEH || CiBao || CBYXB || BWSD || BWSDYXB ? CibaoFormFields : BW || BWYXB ? BwFormFields : HJBWFormFields"
    :rules="formRules"
    hideRequiredMark
    class="flex flex-nowrap query-fields"
    label-align="right"
    layout="inline"
    ref="FormRef"
  >
    <a-form-item label="平台" name="type">
      <div style="display: flex">
        <a-radio-group
          button-style="solid"
          v-model:value="type"
          style="width: 100%"
          @change="typeChange"
          v-if="code !== TypeCode.DF"
        >
          <a-badge count="new" v-if="code === TypeCode.BW">
            <a-radio-button style="border-radius: 0" v-if="code === TypeCode.BW" :value="ProductEnum.BWYXB">
              百搜版
            </a-radio-button>
          </a-badge>
          <a-radio-button v-if="code === TypeCode.BW" :value="ProductEnum.BW">百姓版</a-radio-button>

          <a-radio-button v-if="code === TypeCode.HJ" :value="ProductEnum.HJBW">黄金标王</a-radio-button>
          <a-radio-button v-if="code === TypeCode.WB" :value="ProductEnum.WbBao">精准词词包</a-radio-button>
          <!-- <a-badge count="new" v-if="code === TypeCode.CB">
            <a-radio-button v-if="code === TypeCode.CB" :value="ProductEnum.CBTEH"> 特惠版 </a-radio-button> </a-badge
          >; -->
          <a-badge count="new" v-if="code === TypeCode.CB">
            <a-radio-button v-if="code === TypeCode.CB" :value="ProductEnum.CBYXB">百搜版</a-radio-button>
          </a-badge>
          ;
          <a-radio-button v-if="code === TypeCode.CB" :value="ProductEnum.CiBao">百姓版</a-radio-button>

          <!--          <a-radio-button v-if="code === TypeCode.DF" :value="ProductEnum.DFBEN">百姓版</a-radio-button>-->

          <a-badge count="new" v-if="code === TypeCode.SD">
            <a-radio-button v-if="code === TypeCode.SD" :value="ProductEnum.BWSDYXB">百搜版</a-radio-button>
          </a-badge>
          ;
          <a-radio-button v-if="code === TypeCode.SD" :value="ProductEnum.BWSD">百姓版</a-radio-button>
        </a-radio-group>
        <a-checkbox-group v-model:value="platformIds" v-if="code === TypeCode.DF" style="width: 100%">
          <a-checkbox :value="1">微信视频号</a-checkbox>
          <a-checkbox :value="2">抖音号</a-checkbox>
        </a-checkbox-group>
        <a-button style="border-left: none; border-radius: 0" @click="getBwPro" v-if="code === TypeCode.BW">
          标王官网版
        </a-button>
      </div>
    </a-form-item>
    <a-row class="flex-1" v-if="CiBao || CBYXB || CBTEH || WBTEH || DFTEH || DFTEX || BWSD || BWSDYXB">
      <a-col :span="DFTEH || DFTEX ? 8 : 10">
        <a-form-item name="packageId" label="套餐" class="package-control">
          <a-select
            v-model:value="CibaoFormFields.packageId"
            placeholder="请选择套餐"
            :options="packageList"
            @change="comboChange($event)"
          />
          <!-- {{ CibaoFormFields.packageId }}eess -->
          <!-- <a-select
            v-model:value="CibaoFormFields.packageId"
            placeholder="请选择套餐"
            :options="packageList"
            @change="handlePackageChange"
          /> -->
        </a-form-item>
      </a-col>
      <a-col :span="8" v-if="BWSD || BWSDYXB">
        <a-form-item label="推广区域" @click="sdVisible = true" class="area-disable-sd" name="serviceAreas">
          <a-select
            placeholder="请选择推广区域"
            :max-tag-count="2"
            mode="multiple"
            v-model:value="CibaoFormFields.serviceAreas"
            :options="serviceAreasOptions"
            disabled
          />
        </a-form-item>
      </a-col>
      <a-col :span="6" v-if="WBTEH">
        <a-form-item label="时长" name="comboPriceId">
          <a-select
            allow-clear
            placeholder="请选择推广时长"
            v-model:value="CibaoFormFields.comboPriceId"
            :options="comboPriceList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col>
      <a-col :span="DFTEH || DFTEX ? 8 : 6" v-else>
        <a-form-item label="时长" name="comboPriceId">
          <a-select
            placeholder="请选择推广时长"
            v-model:value="CibaoFormFields.comboPriceId"
            :options="comboPriceList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="CibaoFormFields.packageId === 22 || CibaoFormFields.packageId === 23" :span="8">
        <a-form-item name="oldCustomerAllWebOrderNo" label="编号">
          <a-input v-model:value="CibaoFormFields.oldCustomerAllWebOrderNo" placeholder="请输入订单编号" allow-clear />
        </a-form-item>
      </a-col>
      <!-- {{ mainStore.cibaotaoc }}6685 v-if="mainStore.cibaotaoc == 13"-->
      <a-col
        :span="8"
        v-if="
          route.path === '/price-package-wb' &&
          (CibaoFormFields.packageId == 13 ||
            CibaoFormFields.packageId == 14 ||
            CibaoFormFields.packageId == 34 ||
            CibaoFormFields.packageId == 35)
        "
      >
        <a-form-item name="zzbwOrderNo" label="订单编号">
          <a-input v-model:value="CibaoFormFields.zzbwOrderNo" placeholder="请输入标王或通品订单编号" allow-clear />
        </a-form-item>
      </a-col>
      <div
        style="margin-top: 5px; margin-left: 10px; font-size: 15px"
        v-if="route.path === '/price-package-wb' && CibaoFormFields.packageId == 5"
      >
        <!--        关键词数量: {{ giftNumberses1 }}-->

        <span style="margin-left: 60px">投放地区:全国</span>
      </div>
      <div
        style="margin-top: 30px; margin-left: 2px; font-size: 15px"
        v-if="route.path === '/price-package-wb' && CibaoFormFields.packageId == 13"
      >
        关键词数量: {{ giftNumberses12 }}
        <span style="margin-left: 60px">投放地区:全国</span>
        <span style="margin-left: 185px; color: red">若您输入的订单编号为标王产品，那么投放时长将跟随标王主订单</span>
      </div>
      <div
        style="margin-top: 30px; margin-left: 2px; font-size: 15px"
        v-if="route.path === '/price-package-wb' && CibaoFormFields.packageId == 14"
      >
        关键词数量: {{ giftNumberses123 }}
        <span style="margin-left: 60px">投放地区:全国</span>
        <span style="margin-left: 185px; color: red">若您输入的订单编号为标王产品，那么投放时长将跟随标王主订单</span>
      </div>
    </a-row>
    <div v-if="CiBao" style="position: relative; left: -280px" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitCibao">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>

    <div v-if="CBYXB" style="position: relative; left: -280px" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitCibao">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <div v-if="BWSD || BWSDYXB" style="position: relative" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitEvent">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <div v-if="CBTEH" style="position: relative; left: -150px" class="cibao-submit flex-shrink-0">
      <!-- <a-button type="primary" :loading="submitting" class="mr-2" @click="emit('cibao-submit', { productId: 7 })"
        >查询</a-button
        
      > -->
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitCibao">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <div v-if="DFTEH" style="position: relative; left: -150px" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitCibao">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <div v-if="HJBW" style="position: relative; left: -280px" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="submitCibao">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <a-row class="flex-1 hjbw-flex" v-if="HJBW">
      <a-col :span="8">
        <a-form-item v-if="HJBW" label="推广区域" @click="handleHjbwAreaClick" class="area-disable" name="serviceAreas">
          <a-select
            placeholder="请选择推广区域"
            :max-tag-count="2"
            mode="multiple"
            :value="HJBWFormFields.areas"
            :options="serviceAreasOptions"
            disabled
          />
        </a-form-item>
      </a-col>
      <!-- <a-col :span="8">
        <a-form-item name="searchText" label="关键词">
          <a-input
            allow-clear
            placeholder="请输入关键词"
            :disabled="submitting"
            v-model:value.trim="HJBWFormFields.keyword"
          />
        </a-form-item>
      </a-col> -->
      <a-col :span="8">
        <a-form-item label="落地页" name="comboPriceId">
          <a-select
            allow-clear
            placeholder="请选择落地页"
            v-model:value="HJBWFormFields.shopType"
            :options="LandingPageList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col>
      <!-- <a-col v-if="HJBW" :span="8">
        <a-form-item label="黄展转移" name="comboPriceId" style="margin-top: 10px">
          <a-select
            allow-clear
            placeholder="请选择落地页"
            v-model:value="HJBWFormFields.shopType"
            :options="LandingPageList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="HJBW" :span="8">
        <a-form-item label="备注" name="comboPriceId" style="margin-top: 10px">
          <a-select
            allow-clear
            placeholder="请选择落地页"
            v-model:value="HJBWFormFields.shopType"
            :options="LandingPageList"
            :loading="comboPriceLoading"
          />
        </a-form-item>
      </a-col> -->
    </a-row>
    <div v-if="HJBW" class="cibao-submit flex-shrink-0">
      <a-button type="primary" :loading="submitting" class="mr-2" @click="beforeHjbwSumit">查询</a-button>
      <a-button @click="emit('cibao-reset')">重置</a-button>
    </div>
    <a-form-item
      v-if="BW || BWYXB"
      label="推广区域"
      @click="handleServiceAreaClick"
      class="area-disable"
      name="serviceAreas"
    >
      <a-select
        placeholder="请选择推广区域"
        :max-tag-count="2"
        mode="multiple"
        :value="BwFormFields.serviceAreas"
        :options="serviceAreasOptions"
        disabled
      />
    </a-form-item>
    <a-form-item v-if="BW || BWYXB" label="用户所在地" name="userAreas" class="user-areas">
      <a-select show-search placeholder="请选择用户所在地" v-model:value="userAreas" :options="serviceAreasOptions" />
    </a-form-item>
  </a-form>
  <!-- (DFTEX && route.name === 'price-package-wb') -->
  <a-col style="margin-top: 22px" v-if="CBTEH && isQuarterly" :span="8">
    <a-form-item label="至尊标王编号" name="zzbwOrderNo">
      <a-input v-model:value.trim.number="CibaoFormFields.zzbwOrderNo" placeholder="请输入至尊标王编号" />
    </a-form-item>
  </a-col>
  <a-col
    :span="8"
    style="margin-right: 100px; margin-top: 20px; position: relative; left: 0; top: 0"
    v-if="CiBao || CBYXB || CBTEH || DFTEH || BWSD || BWSDYXB"
  >
    <a-form-item style="width: 1000px" name="searchText">
      <p>
        业务核心词:
        <ForbiddenText :category="type" />
      </p>
      <a-textarea
        :width="300"
        :auto-size="{ minRows: 7, maxRows: 17 }"
        v-model:value="CibaoFormFields.keyword"
        :placeholder="keywordPlaceholder"
      />
    </a-form-item>
  </a-col>

  <a-col :span="8" style="margin-right: 100px; margin-top: 20px; position: relative; left: 0; top: 0" v-if="HJBW">
    <a-form-item style="width: 1000px" name="searchText">
      <p>
        关键词:
        <ForbiddenText :category="type" />
      </p>
      <a-textarea
        :width="300"
        :auto-size="{ minRows: 7, maxRows: 17 }"
        v-model:value="HJBWFormFields.keyword"
        :placeholder="keywordPlaceholder"
      />
    </a-form-item>
  </a-col>
  <div class="mt-4 mb-1" v-if="BW || BWYXB">
    <bw-textarea
      v-model:text="text"
      :submitting="bwSubmitting"
      :type="type"
      @submit="beforeSubmit"
      @reset="handleReset"
    />
  </div>
  <BwArea v-model:show="visible" @change="handleAreaChange" ref="BwAreaRef" />
  <BwArea v-model:show="sdVisible" @change="handleSDAreaChange" ref="SDAreaRef" />
  <BwArea v-model:show="hjbwVisible" @change="handleHjbwAreaChange" ref="HJBwAreaRef" />
</template>
<script lang="ts" setup>
import UserGuide from '@/views/price-sheet/components/UserGuide.vue'
import ForbiddenText from '@/views/price-sheet/components/ForbiddenText.vue'
import { keywordPlaceholder } from '@/shared/text'
import { useVModel } from '@vueuse/core'
import type { PackageData } from '@/services/price-sheet/getPackageList'
import { computed, onMounted, ref, watch } from 'vue'
import BwArea from '@/views/price-sheet/components/BwArea.vue'
import type { BwPriceAskParams } from '@/services/price-sheet/getBwPriceAskWords'
import type { CiBaoPriceAskParams } from '@/services/price-sheet/getKeywordList'
import { type FormInstance, message } from 'ant-design-vue'
import type { ComboPrice, getComboPriceLists } from '@/services/price-sheet/getComboPriceList'
import { isEqual, uniq } from 'lodash-es'
import { useCategory } from '@/hooks/useCategotry'
import { emojiMatcher } from '@/utils'
import { ProductEnum } from '@/core/enums/platform'
import BwTextarea from '@/views/price-sheet/components/BwTextarea.vue'
import { ComboPriceNameEnum } from '@/core/enums/name'
import type { HjbwPriceAskParams } from '@/services/price-sheet/getKeywordListHjbw'
import { TypeCode } from '@/views/price-sheet/price-checking-by-category/type'
import userDetail from '@/services/user/userDetail'
import { useMainStore } from '@/store/useMainStore'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
const route = useRoute()
const mainStore = useMainStore()

interface Props {
  packageList: PackageData[]
  comboPriceList: ComboPrice[]
  HjbwFormFields: HjbwPriceAskParams
  LandingPageList?: any //
  comboPriceLoading: boolean
  submitting: boolean
  bwSubmitting: boolean
  getResult: boolean
  type: ProductEnum
  bw: BwPriceAskParams
  cibao: CiBaoPriceAskParams
  code: string
}
const selectedProductId = ref<number | null>(null) // 新增状态来存储选中的 productId

// function handlePackageChange(packageId: number) {
//   const selectedPackage = props.packageList.find((pkg) => pkg.value === packageId)
//   selectedProductId.value = selectedPackage ? selectedPackage.productId : null // 获取对应的 productId
// }
// 在查询按钮的点击事件中使用 selectedProductId
const submitCibao = () => {
  // console.log(selectedProductId.value, '点击')
  let platformIdsStr = ''
  if (platformIds.value && platformIds.value.length > 0) {
    platformIdsStr = platformIds.value.sort().join(',')
  } else if (route.name === 'price-package-df') {
    // 如果没有选中，至少设置默认值
    platformIdsStr = '1'
  }
  console.log('提交查询时 platformIds:', platformIdsStr, '选中的值:', platformIds.value)
  emit('cibao-submit', { productId: CibaoFormFields.value.packageId, platformIds: platformIdsStr })
}
const submitEvent = () => {
  FormRef.value?.validate().then(() => {
    emit('sd-submit', { productId: CibaoFormFields.value.packageId })
  })
}
const isQuarterly = computed(() => {
  // Replace '季单ID' with the actual ID value for quarterly duration in your comboPriceList
  return CibaoFormFields.value.comboPriceId == 23
})
// const beixuan = ref([
//   {
//     label: '年单',
//     value: 12
//   }
// ])
interface Emits {
  (e: 'cibao-submit'): void
  (e: 'hjbw-submit'): void
  (e: 'cibao-package-change', v: number): void
  (e: 'cibao-reset'): void
  (e: 'bw-reset'): void
  (e: 'bw-submit'): void
  (e: 'bw-reset-with-area'): void
  (e: 'platform-ids-change', v: string): void
}
const emit = defineEmits<Emits>()

const FormRef = ref<FormInstance>()
const BwAreaRef = ref<any>()
const SDAreaRef = ref<any>()
const HJBwAreaRef = ref<any>()
const props = withDefaults(defineProps<Props>(), {
  // type: ProductEnum.BWYXB,
  // type: ProductEnum.CBTEH
  // getResult: false
})
const giftNumberses1 = ref(JSON.parse(localStorage.getItem('giftNumberses1')))
const giftNumberses12 = ref(JSON.parse(localStorage.getItem('giftNumberses2')))
const giftNumberses123 = ref(JSON.parse(localStorage.getItem('giftNumberses123')))
const type = useVModel(props, 'type')
const showNextStep = useVModel(props, 'getResult')
const visible = ref(false)
const sdVisible = ref(false)
const BwFormFields = useVModel(props, 'bw')
const serviceAreas = ref<BwPriceAskParams['serviceAreas']>([])
const CibaoFormFields = useVModel(props, 'cibao')
const HJBWFormFields = useVModel(props, 'HjbwFormFields')
const { CiBao, BW, HJBW, BWYXB, CBYXB, CBTEH, WBTEH, DFTEH, DFTEX, BWSD, BWSDYXB } = useCategory(type)
const platformIds = ref<number[]>([])
const previousPlatformIds = ref<number[]>([]) // 保存上一次的平台选择

onMounted(() => {
  // 检查 CibaoFormFields 中的 comboPriceId 是否有值，如果没有则设置默认值
  //    !CibaoFormFields.value.comboPriceId

  emit('cibao-package-change', 4)
  if (route.name == 'price-package-df') {
    CibaoFormFields.value.comboPriceId = 11 // 设置默认值
    // 默认选中视频号
    if (!platformIds.value || platformIds.value.length === 0) {
      platformIds.value = [1]
      previousPlatformIds.value = [1] // 初始化上一次的值
      console.log('onMounted - 设置默认 platformIds:', platformIds.value)
    }
    // 通知父组件初始的 platformIds
    const platformIdsStr = platformIds.value.sort().join(',')
    emit('platform-ids-change', platformIdsStr)
  }
  // handlePackageChange(packageId: CibaoFormFields.value.comboPriceId)
})
const zzbwOrderNo = ref('')
mainStore.zzbwOrderNods(CibaoFormFields.value)

const formRules = computed(() => {
  if (BW.value || BWYXB.value) {
    return {
      serviceAreas: [{ required: true, message: '请选择推广区域', trigger: 'change' }],
      userAreas: [{ required: true, message: '请选择用户所在地', trigger: 'change' }]
    }
  } else if (BWSD || BWSDYXB) {
    return { serviceAreas: [{ required: true, message: '请选择推广区域', trigger: 'change' }] }
  } else {
    return {}
  }
})
const yues = ref(5)
const text = ref('')

const userAreas = computed({
  set(val?: string) {
    BwFormFields.value.userAreas = val ? [val] : []
  },
  get() {
    return BwFormFields.value.userAreas[0]
  }
})

const serviceAreasOptions = computed(() => {
  return serviceAreas.value.reduce<{ label: string; value: string }[]>((prev, next) => {
    prev.push({
      label: next,
      value: next
    })
    return prev
  }, [])
})

function handleServiceAreaClick() {
  visible.value = true
}

const hjbwVisible = ref(false)
function handleHjbwAreaClick() {
  hjbwVisible.value = true
}

function handleAreaChange(cityMap: Record<string, string[]>) {
  serviceAreas.value = Object.keys(cityMap).reduce<string[]>((data, key) => {
    return data.concat(cityMap[key])
  }, [])

  if (!isEqual(BwFormFields.value.serviceAreas, serviceAreas.value)) {
    showNextStep.value = false

    if (BwAreaRef.value.countryWide) {
      BwFormFields.value.serviceAreas = ['全国']
    } else {
      BwFormFields.value.serviceAreas = serviceAreas.value
    }
  }
}
function handleSDAreaChange(cityMap: Record<string, string[]>) {
  serviceAreas.value = Object.keys(cityMap).reduce<string[]>((data, key) => {
    return data.concat(cityMap[key])
  }, [])

  if (!isEqual(CibaoFormFields.value.serviceAreas, serviceAreas.value)) {
    showNextStep.value = false
    if (SDAreaRef.value.countryWide) {
      CibaoFormFields.value.serviceAreas = ['全国']
    } else {
      CibaoFormFields.value.serviceAreas = serviceAreas.value
    }
  }
}

function handleHjbwAreaChange(cityMap: Record<string, string[]>) {
  serviceAreas.value = Object.keys(cityMap).reduce<string[]>((data, key) => {
    return data.concat(cityMap[key])
  }, [])

  if (!isEqual(HJBWFormFields.value.areas, serviceAreas.value)) {
    showNextStep.value = false

    if (HJBwAreaRef.value.countryWide) {
      HJBWFormFields.value.areas = ['全国']
    } else {
      HJBWFormFields.value.areas = serviceAreas.value
    }
  }
}

function beforeSubmit() {
  if (BW.value || BWYXB.value) {
    FormRef.value?.validate().then(() => {
      if (emojiMatcher(text.value)) {
        return message.error('推广关键词中存在如：表情等非法字符')
      }

      const participle = text.value
        .toLowerCase()
        .split(/[\n\r\s,，;；]+/g)
        .filter((t) => t !== '')

      if (participle.length === 0) {
        message.error('请输入推广关键词')
      } else {
        BwFormFields.value.priceAskWords = uniq(participle)
        emit('bw-submit')
      }
    })
  }
}
//       beforeHjbwSubmit
function beforeHjbwSumit() {
  if (HJBW.value) {
    FormRef.value?.validate().then(() => {
      if (emojiMatcher(HJBWFormFields.value.keyword || '')) {
        return message.error('关键词中存在如：表情等非法字符')
      } else if (HJBWFormFields.value.keyword) {
        HJBWFormFields.value.keyword = HJBWFormFields.value.keyword.toLowerCase()

        emit('hjbw-submit')
      } else {
        return message.error('请输入关键词!')
      }
    })
  }
}

function handleReset() {
  emit('bw-reset')
}

function handleBwReset() {
  text.value = ''
  BwAreaRef.value.handleReset()
}

const handleCibaoReset = () => {
  // 如果是视频号页面，重置 platformIds 为默认值（视频号）
  if (route.name === 'price-package-df') {
    platformIds.value = [1]
    previousPlatformIds.value = [1]
    // 通知父组件 platformIds 已重置
    emit('platform-ids-change', '1')
  } else {
    platformIds.value = []
    previousPlatformIds.value = []
  }
}

const getPlatformIds = () => {
  // 确保返回有效的字符串，如果没有选中任何值，返回空字符串
  console.log('getPlatformIds 被调用，当前 platformIds.value:', platformIds.value)
  if (platformIds.value && platformIds.value.length > 0) {
    const result = platformIds.value.sort().join(',')
    console.log('返回 platformIds:', result)
    return result
  }
  console.log('platformIds 为空，返回空字符串')
  return ''
}

defineExpose({
  handleBwReset,
  handleCibaoReset,
  getPlatformIds
})

watch(
  () => serviceAreasOptions.value,
  (options) => {
    if (!options.some((d) => d.value === userAreas.value)) {
      userAreas.value = ''
    }
  }
)

// 标王pro跳转
const [, userDetailFn] = userDetail()
async function getBwPro() {
  const [err, res] = await userDetailFn({
    id: mainStore.userInfo?.id
  })
  if (!err) {
    if (!res.data.data) {
      window.open('http://bwpro.e-baixing.com/#/price-package')
    } else {
      const user = res.data.data
      window.open('http://bwpro.e-baixing.com/#/price-package?userId=' + user.id + '&token=' + user.password)
    }
  } else {
    message.warning(err.message)
  }
}

// 产品切换
async function typeChange(val: any) {
  const code = val.target.value

  mainStore.banbes(code)
  localStorage.setItem('code', code)

  if (code === ProductEnum.CBTEH) {
    emit('bw-jiekshuj', {
      productId: 7
    })
    localStorage.setItem('productId', 7)
  }
  if (code === 2) {
    emit('bw-jiekshuj', {
      productId: 2
    })
    localStorage.setItem('productId', 2)
  }
  if (code === 6) {
    emit('bw-jiekshuj', {
      productId: 6
    })
    localStorage.setItem('productId', 6)
  }
  if (code === 9) {
    emit('bw-jiekshuj', {
      productId: 9
    })
    localStorage.setItem('productId', 9)
  }
  if (code === 10) {
    emit('bw-jiekshuj', {
      productId: 10
    })
    localStorage.setItem('productId', 10)
  }

  if (code === 12) {
    emit('bw-jiekshuj', {
      productId: 12
    })
    localStorage.setItem('productId', 12)
  }
  if (code === 13) {
    emit('bw-jiekshuj', {
      productId: 13
    })
    localStorage.setItem('productId', 13)
  }
  CibaoFormFields.value.comboPriceId = ''
  CibaoFormFields.value.packageId = ''
  // 如果是视频号页面，重置 platformIds
  if (route.name === 'price-package-df') {
    platformIds.value = [1]
    previousPlatformIds.value = [1]
  } else {
    platformIds.value = []
    previousPlatformIds.value = []
  }
  if (code === ProductEnum.BW || code === ProductEnum.BWYXB) {
    emit('bw-reset')
  } else {
    emit('cibao-reset')
  }
}
const comboChange = (event: any) => {
  CibaoFormFields.value.oldCustomerAllWebOrderNo = ''
  emit('cibao-package-change', event)
}

// 监听平台变化
watch(
  () => platformIds.value,
  (newValue, oldValue) => {
    if (route.name === 'price-package-df') {
      console.log('platformIds 变化:', newValue)

      // 检查是否试图取消所有选项
      if (!newValue || newValue.length === 0) {
        // 恢复到上一次的值
        platformIds.value = previousPlatformIds.value.length > 0 ? [...previousPlatformIds.value] : [1]
        message.error('平台必选')
        return
      }

      // 保存当前有效的选择作为上一次的值
      previousPlatformIds.value = [...newValue]

      // 通知父组件 platformIds 已改变（用于实时更新原价显示）
      const platformIdsStr = newValue.sort().join(',')
      emit('platform-ids-change', platformIdsStr)

      // 当平台变化时，通知父组件重新获取套餐价格列表
      if (CibaoFormFields.value.packageId) {
        emit('cibao-package-change', CibaoFormFields.value.packageId)
      }
    }
  },
  { deep: true }
)

watch(
  () => props.comboPriceList,
  (newValue) => {
    if (route.name == 'price-package-sd') {
      CibaoFormFields.value.comboPriceId = newValue[0]?.value // 设置默认值
    }
  }
)
</script>
<!--  木叶重建  -->
<style lang="scss" scoped>
::v-deep(.ant-scroll-number) {
  z-index: 999;
}

.hjbw-flex {
  display: flex;
  flex-wrap: wrap;
}

.query-fields {
  // height: 32px;
}

.area-disable {
  width: 280px;
  height: 32px;

  ::v-deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
    background: transparent;
    color: inherit;
    cursor: pointer;
  }

  ::v-deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
    color: inherit;
    cursor: pointer;
  }
}

.area-disable-sd {
  height: 32px;

  ::v-deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
    background: transparent;
    color: inherit;
    cursor: pointer;
  }

  ::v-deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
    color: inherit;
    cursor: pointer;
  }
}

.user-areas {
  width: 273px;
  height: 32px;
}

.cibao-submit {
  min-width: 138px;
}

.package-control {
  ::v-deep(.ant-form-item-control) {
    overflow: hidden;
  }
}
</style>
